package com.globalwave.rule.engine;

import java.sql.Types;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;

public class Factor {

    private String bean ;
    private String property ;
    private String convertor ;
    private String value ;
    private int type ;

    public Factor(String property, String convertor, String value, int type) {
	    if (property != null) {
	    	int index = property.indexOf(".") ;
	    	if (index > 0) {
			    this.bean  = property.substring(0, index);
			    this.property = property.substring(index + 1) ;
	    	}
	    }
	    this.convertor = convertor ;
	    this.value = value ;
	    
	    this.type = type ;
    }

    public Object getValue(Map<String, Object> vars) throws Exception {
    	
    	if (bean != null) {
			return PropertyUtils.getProperty(vars.get(bean), property) ;
    	} else {
    		if (Types.INTEGER == type) {
    	    	return Integer.valueOf(value) ;    			
    		} else if (Types.BIGINT == type) {
    	    	return Long.valueOf(value) ;    			
    		} else if (Types.DOUBLE == type) {
    	    	return Double.valueOf(value) ;    			
    		} else if (Types.FLOAT == type) {
    	    	return Float.valueOf(value) ;    			
    		} else if (Types.BOOLEAN == type) {
    	    	return Boolean.valueOf(value) ;    			
    		} else {
    			return value ;
    		}
    	}
    	
    }
    
    public void setValue(Map<String, Object> vars, Object value) throws Exception {
		PropertyUtils.setProperty(vars.get(bean), property, value) ;    	
    }
}
